"""
1. 批量注册用户 register
2. 批量登录用户   login
3. 请求使用设备请求 use_set
4. 获取数据库已注册的用户信息 _account
5. 批量注销用户 del_account
"""
import base64
import datetime
import json
import requests

from common.logger import logger


requests.packages.urllib3.disable_warnings()
log = logger()
session = requests.Session()

def bs64(data):
    data = json.dumps(data, ensure_ascii=False)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')

def decode64_str(data):
    """
    base64解密
    :param data: 需要解密的字符串bytes-like object or ASCII string s
    :return:
    """
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str

# 配置请求头
now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')
header = {"Content-Type": "application/json"}
# https://192.168.10.146:8081
# https://47.102.214.108
# https://192.168.10.233:8081
# ip = 'https://47.102.214.108'
ip = 'https://www.retone-hearing.fit'


def send_post(url, data, cookie=None):
    _ = base64.b64encode(json.dumps(data, ensure_ascii=False).encode('utf-8'))
    if cookie is None:
        res = session.post(url, data=_, verify=False, headers=header)
    else:
        cookies = {"hearingaid_user": cookie}
        res = session.post(url, data=_, verify=False, headers=header, cookies=cookies)
    return res

def login(username, password=None):
    """
    登录接口
    :param username: 用户名
    :param password: 密码
    :return: 返回用户cookie
    """
    user = username
    passwd = password
    # 登录
    login_url = ip + '/microServiceUser/responseEncode/requestDecode/login'
    info = {
        "type": 0,
        "sourcePlatform": "RETONE_FIT",
        "password": 'cc1234',
        "loginObject": user
    }
    res = send_post(login_url, info)
    if res.status_code != 200 or res.json()['data'] is None:
        log.info("=============  登录   接口调用失败=========="+'\n'+str(res.json())+f'res.status_code = {res.status_code}')
    else:
        with open('cookie.txt', mode='a', encoding='utf8') as f:
            f.write(res.cookies.values()[0]+'\n')
        return str(res.cookies.values()[0])

def del_account(user, pswd):
    """
    注销用户
    :return:
    """
    del_url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/getCurrentUserDeleteCode'
    info = {
            "authenticationMethod": "EMAIL"
    }
    cookie = login(user, pswd)
    # log.info(f"登录返回的验证码:{cookie}")
    res = send_post(del_url, info, cookie)
    if res.status_code != 200 or res.json()['data'] is None:
        log.info("=============删除接口获取验证码出现错误 ==============")
        log.info(res.json())
    result = decode64_str(res.json()['data'])
    vilidataCode = json.loads(result)['validateCode']
    # log.info(f"获取验证码: res = {vilidataCode}")
    # 使用验证码注销用户
    upset_user = 'https://192.168.10.146:8081/microServiceUser/needAppUserAuth/responseEncode/requestDecode/deleteCurrentUser'
    _info = {"notice": vilidataCode}
    res = send_post(upset_user, _info, cookie)
    if res.status_code != 200 or res.json()['description'] is not None:
        log.info("=============   注销用户   获取验证码出现错误 ==============")
    else:
        log.info("注销成功")

def get_personal_info(cookie):
    """
    获取各人信息
    :param username: 用户名
    :param passwd: 密码
    :return: 返回mqtt配置信息
    """
    mqtt_url = ip + '/platformRetoneFit/api/needAppUserAuth/responseEncode/requestDecode/getCurrentPersonalInfo'
    info = {}
    # cookie = login(username, passwd)
    res = send_post(mqtt_url, info, cookie)
    if res.status_code != 200 or res.json()['data'] is None:
        log.info(f'=====  获取个人  信息接口失败 =========\n状态码={res.status_code},错误信息={res.json()}')
    else:
        data_str = decode64_str(res.json()['data'])
        data = json.loads(data_str)
    # log.info(dic_conf)
        log.info(f'data={data}')
        return data

def modifypersoninfo(account=None, name=None, gender=None) -> None:
    """
    | account   | String  | chen123  |   否   | 账号。<br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且4-30个字符，非纯数字 |
    | name      | String  | 张三  |   否   |姓名<br>最大长度：20 |
    | gender   | GenderEnum | MALE |   否  | 性别。MALE：男、FEMALE：女、null：空 |
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyPersonInfo'
    data = {
        "account": account,
        "name": name,
        "gender": gender
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] != '200':
        log.info('============= 修改个人信息 接口错误, 请检查================')
        log.info(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        log.info(f'修改信息成功')

def modifypassword(oldPassword, newPassword) -> None:
    """新旧密码
    | oldPassword | String  | 123456 |  是  | 旧密码 |
    | newPassword | String  | 000000 |  是  | 新密码 <br>验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且6-30个字符，必须同时包含数字和字母 |
    :param cookie:
    :param oldPassword:
    :param newPassword:
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyPersonPassword'
    data = {
        "oldPassword": oldPassword,
        "newPassword": newPassword
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] != '200':
        log.info('============= 修改密码 接口错误, 请检查================')
        log.info(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        log.info(f'修改密码成功,新密码:{data["newPassword"]}')

def getLoginState(cookie=None) -> bool:
    """
    :param cookie:
    :return: Ture hou False
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/getLoginState'
    cookies = {"hearingaid_user": cookie}
    res = session.post(url, cookies=cookies, headers=header, verify=False)
    if res.status_code != 200 or res.json()['result'] != '200':
        log.info('============= 获取登录状态 接口错误, 请检查================')
        log.info(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        log.info(f'APP登录状态:{dic["loginState"]}')
        return dic["loginState"]

def getUserLoginObjectState(account, phonecountry=None, sourceplatform=None) -> dict:
    """验证APP用户登录主体是否存在
    | loginObject | String | 18566965369 | 是 |登录对象。可以是账号、手机号、邮箱中的任意一种。 <br>账号验证规则：只允许英文、数字、特殊字符_-+~!@#$%^&*，且4-30个字符，非纯数字<br>手机号长度：4-12位<br>邮箱最大长度：50|
    | phoneCountry | Enum | CN   | 否 | 手机号归属国家(用户登录主体是手机号时必填时必填)<br>CN：中国<br>OTHER：其它|
    | sourcePlatform  | Enum | RETONE_FIT | 是 | 验证来源平台。<br>RETONE_FIT：RetoneFit<br>BLUETOOTH_HA：BluetoothHA<br>WECHAT_HA：WeChatHA|
    :param cookie:
    :return:
    | loginObjectState  | Boolean  | true | 用户登录主体是否存在。true:已存在、false:不存在 |
    | userCancellation  | Boolean  | true | 用户是否是注销状态（只有loginObjectState为true时才有值）。true:注销、false:非注销 |
    """
    url = ip + '/microServiceUser/responseEncode/requestDecode/getUserLoginObjectState'
    data = {
        "loginObject": account,
        "phoneCountry": phonecountry,
        "sourcePlatform": sourceplatform
    }
    res = send_post(url, data)
    if res.status_code != 200 or res.json()['result'] != '200':
        log.info('============= APP用户登录主体是否存在 接口错误, 请检查================')
        log.info(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        log.info(f'用户登录主体是否存在:{dic["loginObjectState"]}, 用户是否是注销状态:{dic["userCancellation"]}')
        return dic

def uploadUserProfile(image_path) -> None:
    """
    上传用户头像
    :param cookie:
    :param files:
    :return:
    """
    url = ip + '/microServiceUser/needAppUserAuth/responseEncode/uploadUserProfile'

    # cookies = {"hearingaid_user": cookie}
    with open(image_path, mode='rb') as image:
        image_rb = image.read()
    files = {'file': image_rb}
    res = send_post(url, files=files)
    if res.status_code != 200 or res.json()['data'] is None:
        log.info('============= 上传文件 接口错误, 请检查================')
        log.info(f'返回状态码:{res.status_code},错误的内容:{res.text}')
    else:
        dic = json.loads(decode64_str(res.json()['data']))
        log.info(f'文件路径:{dic["filePath"]}, 文件展示路径:{dic["filePathShow"]}')
        return dic



"""
retonet fit
"""
def addmemo(cookie):
    """
    | note      | String  | 记得煮饭  |   是   |提醒内容<br>最大长度：255个字符 |
    | activeTime| String  | 2021-03-26 08:23:20  |   是   |提醒时间 格式："yyyy-MM-dd HH:mm:ss" 【注意：app上传时间为0时区时间】|
    | memoTypeEnum   | Enum | NEVER_REPEAT |   是  | 备忘录类型。<br>NEVER_REPEAT：不重复、<br>EVERY_DAY：每天、
    <br>WORK_DAY：工作日（周一-周五）、<br>REST_DAY：休息日（周六-周日）、<br>DAY_OF_WEEK：每周指定时间（周一-周日） |
    | dayOfWeeks  | List<Enum> | ["SUNDAY"] |   否  | 每周指定时间（周一-周日）。只有在“备忘录类型”是 “每周指定时间”的情况下才必填。
    <br>SUNDAY：周日<br>MONDAY：周一<br>TUESDAY：周二<br>WEDNESDAY：周三<br>THURSDAY：周四<br>FRIDAY：周五<br>SATURDAY：周六|
    :return:
    """
    addmemo_url = ip + '/api/memo/needAppUserAuth/responseEncode/requestDecode/addMemo'
    info = {
        "note": "出门",
        "activeTime": '2023-02-15 11:11:00',
        "memoTypeEnum": "EVERY_DAY"
    }
    res = send_post(addmemo_url, data=info, cookie=cookie)


def bind_set(cookie, devicenum):
    """
    绑定设备 设备型号可以随机生成
    :return: 返回绑定设备
    """
    bind_set_url = ip + '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/binding'
    info = {
    "deviceNumber":devicenum,
    "deviceTypeCode": "1",
    "chipTypeCode":"1"
    }
    res = send_post(bind_set_url, info, cookie)
    if res.status_code != 200 or res.json()['description'] is not None:
        log.info("============= 绑定设备 错误==========")
        log.info(res.json())
    return info['deviceNumber']

def use_set(cookie, devicenum):
    """
    使用设备的信息, 使用设备的用户
    :param cookie: 用户
    :return:
    """
    user_set_url = ip+'/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/deviceUse'
    info = {
    "leftDevice": {
        "deviceNumber": devicenum,
        "firmwareVersion": "1.0.38"
    },
    "rightDevice": {
        "deviceNumber": devicenum,
        "firmwareVersion": "1.0.38"
    }
    }
    res = send_post(user_set_url, info, cookie)
    # data = decode64_str(res.json()['data'])
    # data = json.loads(data)
    if res.status_code != 200 or res.json()['data'] is None:
        log.info('===使用设备接口 错误== ')
        log.info(res.json())

def check_device(cookie):
    check_devices_url = ip + '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/getDeviceBindingList'
    info = {}
    res = send_post(check_devices_url, info, cookie)
    if res.status_code !=200 or res.json()['data'] is None:
        log.info(res.json())
        return ('==========查询绑定设备信息出现错误  =====')
    data = decode64_str(res.json()['data'])
    data = json.loads(data)
    log.info(data)



if __name__ == '__main__':

    # 注册一个verify1@qq.com的账号,在平台上注册WECHAT_HA
    cookie = login('tester0', 'cc1234')
    getLoginState(cookie)


